package com.enzoism.testspring.transaction.tx;

import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyFactory implements InvocationHandler {

    public Object target;

    Advice advisor = new MyTransactionInterceptor();

    public ProxyFactory(Object target) {
        this.target = target;
    }
    
    
    
    /*private static class ProxyFactoryClient {
        private static final ProxyFactory PROXY_FACTORY = new ProxyFactory();
    }*/

    /**
     * 创建代理
     */
    public <T> T createProxy(Class<?> target) {
        return (T) Proxy.newProxyInstance(getClassLoader(), getMethodInterceptor(target), this);
    }

    private Class[] getMethodInterceptor(Class<?> target) {
        return target.getInterfaces();
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        MethodInvocation methodInvocation = new TransactionMethodInvocation(args, target, method, this.advisor);
        return methodInvocation.proceed();
    }


    private ClassLoader getClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }

}